<%@ page language="java" contentType="text/html; charset=UTF-8"	 pageEncoding="UTF-8"%>
<%@ include file="../include/laypublic.jsp"%>
<!DOCTYPE html>
<html>
<head>
</head>
  <title>公司管理</title>
  <style type="text/css">
  	.layui-form-select dl{
		max-height: 150px; // 原值为300，调节高度建议为50的倍数
	}
  </style>
</head>
<body>
  <div class="layui-fluid">   
    <div class="layui-card">
      <!-- 查询区域  -->
      <div id="query-form" class="layui-form layui-card-header layuiadmin-card-header-auto">
        <div class="layui-form-item">
          <div class="layui-inline">
            <label class="layui-form-label">公司名称</label>
            <div class="layui-input-inline">
              <input type="text" name="compName" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
          </div>
          <div class="layui-inline">
            <label class="layui-form-label">所属省份</label>
            <div class="layui-input-inline">
              	<select id="query-form-provinceId" name="provinceId" lay-filter="selectCityByPro">
			    	<option value="">请选择-所属省份</option>
					<c:if test="${not empty provinces}">
						<c:forEach var="prov" items="${provinces}" > 
							<option value="${prov.id}" >${prov.sname}</option>
						</c:forEach>
					</c:if>
				</select>
            </div>
          </div>
          <div class="layui-inline">
            <label class="layui-form-label">所属城市</label>
            <div class="layui-input-inline">
              	<select name="cityId" id ="queryCity" lay-filter="selectAreaByCity">
				</select>
            </div>
          </div>
          <div class="layui-inline">
            <label class="layui-form-label">所属区县</label>
            <div class="layui-input-inline">
              	<select name="areaId" id ="queryArea">
				</select>
            </div>
          </div>
          <div class="layui-inline">
            <label class="layui-form-label">状态</label>
            <div class="layui-input-inline">
              <infopub:select id="query-form-state" entireName="-状态" name="state" type="dic" groupNo="A00010020"></infopub:select>
            </div>
          </div>
          <shiro:hasPermission name="LIST_ORG">
	          <div class="layui-inline">
	            <button class="layui-btn layuiadmin-btn-admin" lay-submit lay-filter="LAY-org-search">
	              <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>查询
	            </button>
	            <button class="layui-btn layuiadmin-btn-admin" lay-submit lay-filter="LAY-user-back-reset">
	              <i class="layui-icon layui-icon-fonts-clear  layuiadmin-button-btn"></i>重置
	            </button>
	          </div>
          </shiro:hasPermission>
        </div>
      </div>
  	  <!-- 按钮区域  -->
      <div class="layui-card-body">
        <div style="padding-bottom: 10px;">
          <shiro:hasPermission name="SAVE_ORG">
          	<button class="layui-btn layuiadmin-btn-admin " data-type="add">
          	 <i class="layui-icon layui-icon-add-1 layuiadmin-button-btn"></i>新增
          	</button>
          </shiro:hasPermission>
        </div>
        <!-- 数据表单 -->
        <table id="LAY-org-manage" lay-filter="LAY-org-manage"></table>
        
        <div class="layui-form" lay-filter="add_form" id="add_form" style="padding: 20px 30px 0 0;display:none">
		    <div class="layui-form-item">
		      <label class="layui-form-label">公司名称</label>
		      <div class="layui-input-block">
		        <input type="text" name="compName" maxlength="50" lay-verify="required|CHS" placeholder="请输入公司名称" autocomplete="off" class="layui-input">
		      </div>
		    </div>
		    <div class="layui-form-item">
		    	<label class="layui-form-label">省份</label>
			    <div class="layui-input-block">
				    <select name="provinceId" lay-filter="chooseCityByPro" id ="choosep" lay-verify="required">
				    	<option value="">请选择</option>
						<c:if test="${not empty provinces}">
							<c:forEach var="prov" items="${provinces}" > 
								<option value="${prov.id}" >${prov.sname}</option>
							</c:forEach>
						</c:if>
					</select>
					<input name="provinceName" type="hidden"/>
			    </div>
		  	</div>
		    <div class="layui-form-item">
		    	<label class="layui-form-label">城市</label>
			    <div class="layui-input-block">
					<select name="cityId" lay-filter="chooseCity" id ="selectCity" lay-verify="required">
					</select>
					<input name="cityName" type="hidden"/>
			    </div>
		  	</div>
		    <div class="layui-form-item layui-hide">
		      <input type="button" lay-submit lay-filter="add_form_submit" id="add_form_submit" value="确认">
		    </div>
	  	</div>
	  	
	  	<!-- 编辑窗口 -->
        <div class="layui-form" lay-filter="edit_form" id="edit_form" style="padding: 20px 30px 0 0;display:none">
        	<input type="hidden" name="id" id="editAccountId" />
		    <div class="layui-form-item">
		      	<label class="layui-form-label">公司名称</label>
		      	<div class="layui-input-block">
		        	<input type="text" name="compName" maxlength="50" lay-verify="required|CHS" placeholder="请输入姓名" autocomplete="off" class="layui-input">
		      	</div>
		    </div>
		    <div class="layui-form-item">
		      	<label class="layui-form-label">省份</label>
		      	<div class="layui-input-block">
			      	<select name="provinceId" lay-filter="editCityByPro" id ="editPro" lay-verify="required">
			    		<option value="">请选择</option>
						<c:if test="${not empty provinces}">
							<c:forEach var="prov" items="${provinces}" > 
								<option value="${prov.id}" >${prov.sname}</option>
							</c:forEach>
						</c:if>
					</select>
					<input name="provinceName" type="hidden"/>
				</div>
		    </div>
		    <div class="layui-form-item">
		    	<label class="layui-form-label">城市</label>
			    <div class="layui-input-block">
					<select name="cityId" lay-filter="editCity" id ="editCity" lay-verify="required">
					</select>
					<input name="cityName" type="hidden"/>
			    </div>
		  	</div>
		    <div class="layui-form-item layui-hide">
		      <input type="button" lay-submit lay-filter="edit_form_submit" id="edit_form_submit" value="确认">
		    </div>
	  	</div>
	  	
      </div>
    </div>
  </div>

  <script>
  	layui.config({
    	base: '${ctx}/resources/layuiadmin/' //静态资源所在路径
  	}).extend({
    	index: 'lib/index' //主入口模块
  	}).use(['index', 'table', 'set', 'transfer'], function(){
    	var $ = layui.$
    	,form = layui.form
    	,table = layui.table;
 		// 正则校验
    	form.verify({
    		//验证汉字
    	    CHS: [
    	    	/^[\u0391-\uFFE5]+$/
    	    	,'只能输入汉字'
    	  	]
		});

    	// 表单
    	table.render({
      		elem: '#LAY-org-manage'
      		,url: basePath + '/org/queryByCondition' //请求数据接口
      		,cols: [[
        		{type: 'checkbox', fixed: 'left'}
        		,{field: 'compCode', title: '公司ID'}
        		,{field: 'compName', title: '公司名称'}
        		,{field: 'provinceName', title: '所在省份'}
        		,{field: 'cityName', title: '所在城市'}
        		,{field: 'addTime', title: '创建时间', templet: function(d){
            		  	return layui.util.toDateString(d.addTime,"yyyy-MM-dd HH:mm:ss");
	              	}
	             }
        		,{field: 'state', title: '状态', templet: function (d) {
	        			if(d.state==1){
	          				return "启用中";
	          			}else{return '<span class="layui-badge layui-bg-cyan">已停用</span>' ;}
		        	}
 		    	}
        		,{title: '操作', width: 250, align:'center', fixed: 'right', templet: function(d){
      	  				var optStr ="";
      	  				<shiro:hasPermission name="SAVE_ORG">
      	  					if(d.compCode != 'GS000001'){//默认保理公司不可修改
	      	 					optStr += '<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
      	  					}else{
      	  						optStr += '<a class="layui-btn layui-btn-disabled layui-btn-xs"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
      	  					}
  	  	  				</shiro:hasPermission>
  	  	  				<shiro:hasPermission name="UPDATE_ORG_STATUS">
		  	  	  			if(d.state == 0){//停用
		  	  	  				if(d.compCode != 'GS000001'){
	      	 						optStr += '<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="use"><i class="layui-icon layui-icon-edit"></i>启用</a>';
		  	  	  				}else{
	      	 						optStr += '<a class="layui-btn layui-btn-disabled layui-btn-xs" lay-event="use"><i class="layui-icon layui-icon-edit"></i>启用</a>';
		  	  	  				}
		   	        		}else if(d.state == 1){//启用
		   	        			if(d.compCode != 'GS000001'){
	      	 						optStr += '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="freeze"><i class="layui-icon layui-icon-edit"></i>停用</a>';
		   	        			}else{
	      	 						optStr += '<a class="layui-btn layui-btn-disabled layui-btn-xs" lay-event="freeze"><i class="layui-icon layui-icon-edit"></i>停用</a>';
		   	        			}
		   	        		}
						</shiro:hasPermission>
			  		  	return optStr;
        			}
        		}
      			]]
      		,page: true
      		,limit: 10
    	});
    
    	<shiro:hasPermission name="LIST_ORG">
	    	//监听搜索
	    	form.on('submit(LAY-org-search)', function(data){
		      	//执行重载
		      	table.reload('LAY-org-manage', {page: {curr: 1},
		        	where: trimData(data)
		      	});
	    	});
	    	//重置清空
		    form.on('submit(LAY-user-back-reset)', function(data){
		    	reset_form('query-form');
		    	//额外处理select
				$("#query-form-state").val('');
				$("#queryCity").val('');
				$('#queryCity').html('');
				$("#query-form-provinceId").val('');
				form.render();
		    });
    	</shiro:hasPermission>
    
    	// 监听操作列
    	table.on('tool(LAY-org-manage)', function(obj){
      		var data = obj.data;
      		if(obj.event === 'use'){
          		layer.confirm('确定启用？',{icon:3, title :'提示'}, function(index){
          			$.ajax({
  						type : 'post',
  						url : basePath + '/org/updateStatus?id=' + data.id,
  						success:function(result){
  							if(result.success){
  								table.reload('LAY-org-manage'); //数据刷新
  								layer.close(index);
  							}else{
  								layer.msg(result.msg,{icon: 7});
  				  			}
  						}
  					});
          		});
      		}else if(obj.event === 'freeze'){
          		layer.confirm('确定停用？',{icon:3, title :'提示'}, function(index){
          			$.ajax({
  						type : 'post',
  						url : basePath + '/org/updateStatus?id=' + data.id,
  						success:function(result){
  							if(result.success){
  								table.reload('LAY-org-manage'); //数据刷新
  								layer.close(index);
  							}else{
  								layer.msg(result.msg,{icon: 7});
  				  			}
  						}
  					});
          		});
      		} else if(obj.event === 'edit'){
      			form.val('edit_form',data); // 填充原值
      			$('#editCity').html('');
      			$.ajax({
      				type : "POST", //提交方式  
      				url : "${ctx}/org/getCityByPro",//路径  
      				data : {
      					"provinceCode" :data.provinceId
      				},//数据，这里使用的是Json格式进行传输  
      				success : function(result) {//返回数据根据结果进行相应的处理 
      					if(result.flag==true){
      						var strBuffer = "";
      						layui.$.each(result.citys, function(i,item){
      							strBuffer+= '<option value='+item.id;
      							if(item.id == data.cityId){
      								strBuffer+= ' selected';
      								$('input[name=cityName]').val(item.sname);
      							}
      							strBuffer+= '>'+item.sname+'</option>';
      				        });
      						$('#editCity').append(strBuffer);
      						form.render();
      					}else{
      						layer.msg('数据通信异常~',{icon: 0});
      					}
      				}  
      			});
      			layer.open({
            		type: 1
            		,title: '编辑公司'
            		,content: $('#edit_form')
            		,area: layui.admin.screen() < 2 ? ['80%', '360px'] : ['420px','360px']
            		,btn: ['确定', '取消']
            		,btnAlign: 'c'
            		,yes: function(index, layero){
          	  			var submitID = 'edit_form_submit'
          		  		,submit = layero.contents().find('#'+ submitID);
          	  			//监听提交
          	  			form.on('submit('+ submitID +')', function(data){
                			var field = data.field; //获取提交的字段
                			//提交 Ajax 成功后，静态更新表格中的数据
                			$.ajax({
                    			type : 'post',
  								url : basePath + '/org/save',
                    			data: field,
  								success:function(result){
  									if(result.success){
                						table.reload('LAY-org-manage'); //数据刷新
                						layer.close(index); //关闭弹层
  									}else{
  										layer.msg(result.msg,{icon: 7});
  					  				}
  								}
                			});
              			});  
              		submit.trigger('click');
           		}
          	});
       	}
    	});
    
    // 按钮事件
    var active = {
      add: function(){
        layer.open({
          type: 1
          ,title: '添加公司'
          ,content: $('#add_form')
          ,area: layui.admin.screen() < 2 ? ['80%', '420px'] : ['420px','420px']
          ,btn: ['确定', '取消']
          ,btnAlign: 'c'
          ,yes: function(index, layero){
        	  var submitID = 'add_form_submit'
            	,submit = layero.contents().find('#'+ submitID);

              //监听提交
           	  form.on('submit('+ submitID +')', function(data){
              	var field = data.field; //获取提交的字段
              	//提交 Ajax 成功后，静态更新表格中的数据
              	$.ajax({
                  	type : 'post',
					url : basePath + '/org/save',
                  	data: field,
					success:function(result){
						if(result.success){
              				table.reload('LAY-org-manage'); //数据刷新
              				clean_form("add_form");//清空表单
              				layer.close(index); //关闭弹层
						}else{
							layer.msg(result.msg,{icon: 7});
					  	}
					}
              	});
            });  
            submit.trigger('click');
          }
        }); 
      }
    }  
    // data-type事件
    $('.layui-btn.layuiadmin-btn-admin').on('click', function(){
      var type = $(this).data('type');
      active[type] ? active[type].call(this) : '';
    });
    
 	//查询条件-省份select监听
    form.on('select(selectCityByPro)', function(data){
    	var provinceCode = data.value;
    	$('#queryCity').html('');
		$.ajax({
			type : "POST", //提交方式  
			url : "${ctx}/org/getCityByPro",//路径  
			data : {
				"provinceCode" :provinceCode
			},//数据，这里使用的是Json格式进行传输  
			success : function(result) {//返回数据根据结果进行相应的处理 
				if(result.flag==true){
					var strBuffer = "";
					layui.$.each(result.citys, function(i,item){
						strBuffer+= '<option value='+item.id+'>'+item.sname+'</option>';
						if(i == 0){
							$('#queryArea').html('');
							$.ajax({
								type : "POST", //提交方式  
								url : "${ctx}/org/getAreaByCity",//路径  
								data : {
									"cityCode" :item.id
								},//数据，这里使用的是Json格式进行传输  
								success : function(result) {//返回数据根据结果进行相应的处理 
									if(result.flag==true){
										var strBuffer = "";
										layui.$.each(result.areas, function(i,item){
											if(item.id != null && item.sname != null){
												strBuffer+= '<option value='+item.id+'>'+item.sname+'</option>';
											}
								        });
										$('#queryArea').append(strBuffer);
										form.render();
									}else{
										layer.msg('数据通信异常~',{icon: 0});
									}
								} 
							});
						}
			        });
					$('#queryCity').append(strBuffer);
					form.render();
				}else{
					layer.msg('数据通信异常~',{icon: 0});
				}
			} 
		});
	});
 	//查询条件-省份select监听
    form.on('select(selectAreaByCity)', function(data){
    	var cityCode = data.value;
    	$('#queryArea').html('');
		$.ajax({
			type : "POST", //提交方式  
			url : "${ctx}/org/getAreaByCity",//路径  
			data : {
				"cityCode" :cityCode
			},//数据，这里使用的是Json格式进行传输  
			success : function(result) {//返回数据根据结果进行相应的处理 
				if(result.flag==true){
					var strBuffer = "";
					layui.$.each(result.areas, function(i,item){
						if(item.id != null && item.sname != null){
							strBuffer+= '<option value='+item.id+'>'+item.sname+'</option>';
						}
			        });
					$('#queryArea').append(strBuffer);
					form.render();
				}else{
					layer.msg('数据通信异常~',{icon: 0});
				}
			} 
		});
	});
 	//新增-省份select监听
    form.on('select(chooseCityByPro)', function(data){
    	var provinceCode = data.value;
    	var provinceName = $("#choosep option:selected").text();
    	$('input[name=provinceName]').val(provinceName);
    	$('#selectCity').html('');
		$.ajax({
			type : "POST", //提交方式  
			url : "${ctx}/org/getCityByPro",//路径  
			data : {
				"provinceCode" :provinceCode
			},//数据，这里使用的是Json格式进行传输  
			success : function(result) {//返回数据根据结果进行相应的处理 
				if(result.flag==true){
					var strBuffer = "";
					layui.$.each(result.citys, function(i,item){
						strBuffer+= '<option value='+item.id+'>'+item.sname+'</option>';
			        });
					//默认选中对应省份下的第一个城市
					if(result.citys.length > 0){
						$('input[name=cityName]').val(result.citys[0].sname);
					}
					$('#selectCity').append(strBuffer);
					form.render();
				}else{
					layer.msg('数据通信异常~',{icon: 0});
				}
			},
			error:function (result){ 
				layer.msg('数据通信异常~',{icon: 0});
			}   
		});
	});
 	
  	//新增-城市select监听
    form.on('select(chooseCity)', function(data){
    	var cityName = $("#selectCity option:selected").text();
		$('input[name=cityName]').val(cityName);
	});
    
    //编辑-省份select监听
    form.on('select(editCityByPro)', function(data){
    	var provinceCode = data.value;
    	var provinceName = $("#editPro option:selected").text();
    	$('input[name=provinceName]').val(provinceName);
    	$('#editCity').html('');
		$.ajax({
			type : "POST", //提交方式  
			url : "${ctx}/org/getCityByPro",//路径  
			data : {
				"provinceCode" :provinceCode
			},//数据，这里使用的是Json格式进行传输  
			success : function(result) {//返回数据根据结果进行相应的处理 
				if(result.flag==true){
					var strBuffer = "";
					layui.$.each(result.citys, function(i,item){
						strBuffer+= '<option value='+item.id+'>'+item.sname+'</option>';
			        });
					//默认选中对应省份下的第一个城市
					if(result.citys.length > 0){
						$('input[name=cityName]').val(result.citys[0].sname);
					}
					$('#editCity').append(strBuffer);
					form.render();
				}else{
					layer.msg('数据通信异常~',{icon: 0});
				}
			},
			error:function (result){ 
				layer.msg('数据通信异常~',{icon: 0});
			}   
		});
	});
    
  	//编辑-城市select监听
    form.on('select(editCity)', function(data){
    	var cityName = $("#editCity option:selected").text();
		$('input[name=cityName]').val(cityName);
	});
  });
  	
  	var $ = layui.$;
  	var layer = layui.layer;
  	/**校验公司名是否存在（新增时使用）*/
	function checkCompName(obj){
		var flag = true;
		$.post(
				"${ctx}/org/checkCompNameIsExist",
				{
					"compName":obj.value
				},
				function(data){//data: true 公司名已存在, false 公司名不存在
					if(data){//符合格式,到后台校验 输入的公司名,是否存在
						layer.alert('该公司已存在',{icon: 0});
						flag = false;
					}
				});
		return flag;
	}
	/**校验公司名是否存在（编辑时使用）*/
	function checkNewCompName(obj){
		var flag = true;
		$.post(
				"${ctx}/org/checkNewCompNameIsExist",
				{
					"compName":obj.value,
					"id":$("#editAccountId").val()
				},
				function(data){//data: true 手机号被占用, false 手机号未被占用
					if(data){//符合格式,到后台校验 输入的新手机号,是否被占用
						layer.alert('该公司已存在',{icon: 0});
						flag = false;
					}
					
				});
		return flag;
	}
  </script>
</body>
</html>

